package com.crm.dao.saling;

import com.crm.pojo.PlaningBack;
import com.crm.vo.PlaningBackClientContractUserInfoVO;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created by dr5hx on 2018/8/10
 */
public interface PlaningBackDao extends CrudRepository<PlaningBack, Long> {
    /**
     * 显示回款列表
     *
     * @return
     */
    @Query("from PlaningBack  p where p.planingBackIsDel='否'")
    public List<PlaningBack> showPlaningBackList();


    /**
     * 查询对应合同的对应回款列表
     *
     * @return
     */
    @Query("from PlaningBack p where p.fkPlaningBackOrderId=?1 and p.planingBackIsDel='否'")
    public List<PlaningBack> getPlaningBackByContractId(BigDecimal contractId);

    /**
     * 删除一个回款计划
     *
     * @param pId
     */
    @Query("update PlaningBack p set p.planingBackIsDel='是' where p.planingBackId=?1")
    @Modifying
    public void deletePlaningBackByPlaningBackId(Long pId);

    /**
     * 统计除对应合同的所有回款计划金额
     *
     * @param contractId
     * @return
     */
    @Query("select  sum(planingBack.planingBackMoney) from PlaningBack planingBack where planingBack.fkPlaningBackOrderId=?1")
    public BigDecimal countPlaningBackMoneyByContractId(BigDecimal contractId);

    /**
     * 设置计划回款已回款
     *
     * @param planingBackId
     */
    @Query("update PlaningBack p set p.planingBackIsBack='是' where p.planingBackId=?1")
    @Modifying
    public void setPlaningBackMoneyAlreadyBack(Long planingBackId);

    /**
     * 查询一条未删除的计划汇款记录
     *
     * @param planingBack
     * @return
     */
    @Query("from PlaningBack  planingBack where planingBack.planingBackIsDel='否' and" +
            " planingBack.planingBackId=?1")
    public PlaningBack getPlaningBackRecord(Long planingBack);

    /**
     * 获取计划回款列表
     *
     * @param pageable
     * @return
     */
    @Query("select new com.crm.vo.PlaningBackClientContractUserInfoVO(planingBack,clientInfo,contract,userInfo) from PlaningBack planingBack,Contract contract,Userinfo userInfo,ClientInfo clientInfo " +
            "where planingBack.fkPlaningBackOrderId=contract.contractId and planingBack.planingBackIsDel='否' " +
            "and contract.fkCustomerId=clientInfo.cid and contract.contractEmpno=userInfo.uId")
    public List<PlaningBackClientContractUserInfoVO> getPlaningBackClientContractUserInfoVOList(Pageable pageable);

    /**
     * 获取回款列表的数量
     *
     * @return
     */
    @Query("select count(planingBack) from PlaningBack  planingBack where planingBack.planingBackIsDel='否'")
    public Long getPlaningBackCount();
}
